import { Resizable } from 'react-resizable';
import React, { useEffect, useState } from 'react';
import {
  ProFormText,
  ProFormRadio,
  ProFormDateTimePicker,
} from '@ant-design/pro-components';
import { Modal } from 'antd';
import { request } from 'umi';
import '../leave/leave.less';
import axios from 'axios';
import { SearchOutline } from 'antd-mobile-icons';
import { Table, Input, Button } from 'antd';
export default function applyLeave(props) {
  
  // 原单据编号
  const [anumber, setAnumber] = useState('');
  // 现单据编号
  const [tnumber, setTnumber] = useState('');
  // 员工名称
  const [aname, setAname] = useState('张研');
  // 员工部门
  const [department, setDepartment] = useState('总经办');
  // 员工岗位
  const [prodepartment, setProdepartment] = useState('总经理');
  // 销假时间
  const [cancellationTime, setCancellationTime] = useState(
    getFormatDate(new Date()),
  );
  // 已修天数
  const [oldDays, setOldDay] = useState();
  // 开始时间
  const [startTime, setStartTime] = useState();
  // 结束时间
  const [endTime, setEndtTime] = useState();
  // 实际开始时间
  const [startTimeV, setStartTimeV] = useState();
  // 实际结束时间
  const [endTimeV, setEndtTimeV] = useState();
  // 是否已休假
  const [Iscancellation, setIscancellation] = useState('是');
  // 销假事由
  const [technological, setTechnological] = useState('');
  // 提示框
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 原请假流程
  const [isApplyModalOpen, setIsApplyModalOpen] = useState(false);
  // 提示文字
  const [keyWord, setKeyWord] = useState('');
  const [id,setId] = useState()
  useEffect(()=>{
      let id = props.history.location.state.selectedRowKeys[0]
      console.log(id,14);
      setId(id)
      axios.get(`/api/ljf/updateationLeave/list?id=${id}`).then(val=>{
          console.log(val.data.data[0],'修改请假数据');
            let data = val.data.data[0]
            // setIsApplyModalOpen(data.tnumber)
            setAnumber(data.tnumber)
            setStartTime(data.startTimeV)
            setEndtTime(data.endTimeV)
            setTnumber(data.anumber);
            setTechnological(data.technological)
      })
  },[])
  // 取消弹框
  const handleCancel = () => {

    
    if (endTime) {
      props.history.push('/person/cancellation')
      setIsModalOpen(false);
      setIsApplyModalOpen(false);
    } else {
      setIsModalOpen(false);
      setIsApplyModalOpen(false);
    }
    
  };
      //点击x关闭模态框
      const ModalFalse = () => {
        setIsModalOpen(false);
      };
  // 标准时间
  function getFormatDate(defaultdate: any) {
    let date = defaultdate;
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    hour = hour < 10 ? '0' + hour : hour;
    minutes = minutes < 10 ? '0' + minutes : minutes;
    seconds = seconds < 10 ? '0' + seconds : seconds;
    let currentDate =
      year +
      '-' +
      month +
      '-' +
      day +
      ' ' +
      hour +
      ':' +
      minutes +
      ':' +
      seconds;
    return currentDate;
  }
  // 点击保存
  const applySubmit = () => {
    if (!startTimeV) {
      setIsModalOpen(true);
      setKeyWord('实际开始时间');
    } else if (!endTime) {
      setIsModalOpen(true);
      setKeyWord('实际结束时间');
    } else {
      const number = [
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'G',
        'K',
        'U',
        'V',
        'W',
        'R',
        'S',
        'T',
        'O',
        'P',
        'Q',
        'N',
        'M',
        'Z',
        'X',
        'Y',
        'J',
      ];
      const math = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
      let num = '';
      for (let a = 0; a <= 4; a++) {
        num += number[Math.ceil(Math.random() * 25)];
      }
      num += String(new Date()).split(' ')[3];
      for (let a = 0; a <= 3; a++) {
        num += math[Math.ceil(Math.random() * 9)];
      }
      // setTnumber(num);
      const end = Number(String(endTimeV).split(' ')[2]);
      const start = Number(String(startTimeV).split(' ')[2]);
      const eh = Number(String(endTimeV).split(' ')[4].split(':')[0]);
      const sh = Number(String(startTimeV).split(' ')[4].split(':')[0]);
      const day: any = end - start;
      const h: any = eh - sh;
      const starts: any = getFormatDate(startTimeV);
      const ends: any = getFormatDate(endTimeV);
      setStartTimeV(starts);
      setEndtTimeV(ends);
      var d: any = '';
      if (h > 0 && day > 0) {
        d += day + '天' + h + '小时';
      } else if (h > 0 && day === 0) {
        d += h + '小时';
      } else if (h === 0 && day > 0) {
        d += day + '天';
      }
      setOldDay(d);
      const body = {
        anumber,
        aname,
        department,
        prodepartment,
        cancellationTime,
        oldDays: d,
        applyTime: getFormatDate(new Date()),
        startTimeV: starts,
        endTimeV: ends,
        technological,
        tnumber: num,
        Iscancellation,
        dtype: '销假',
        status: '未提交',
      };
    //   request('/api/ljf/cancellationLeave', {
    //     method: 'post',
    //     data: body,
    //   }).then((res) => {
    //     if (res.code === 200) {
    //       setIsModalOpen(true);
    //       setKeyWord('保存数据成功');
    //     }
    //   });
    // }
    axios.post(`/api/ljf/updateationLeave/?id=${id}`,body).then(val=>{
        if(val.data.code===200){
            setIsModalOpen(true);
            setKeyWord('保存数据成功');
           }
    })
}
  };
  const [acolumns, setAcolumns] = useState([
    {
      title: '序号',
      key: '_id',
      width: 40,
      render: (text, record, index) => <>{index + 1}</>,
      ellipsis: true,
    },
    {
      title: '单据编号',
      key: 'anumber',
      width: 120,
      dataIndex: 'anumber',
      ellipsis: true,
    },
    {
      title: '请假人',
      dataIndex: 'aname',
      key: 'aname',
      ellipsis: true,
      width: 100,
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      ellipsis: true,
      width: 100,
    },
    {
      title: '职位',
      dataIndex: 'prodepartment',
      key: 'prodepartment',
      ellipsis: true,
      width: 100,
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      key: 'startTime',
      ellipsis: true,
      width: 100,
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      key: 'endTime',
      ellipsis: true,
      width: 100,
    },
    {
      title: '请假类型',
      dataIndex: 'applyType',
      key: 'applyType',
      ellipsis: true,
      width: 100,
    },
  ]);
  const [components, setComponents] = useState({});
  const [cancellation, setCancellation] = useState([]); //  总数据渲染
  useEffect(() => {
    request('/api/ljf/apply').then((res: any) => {
      setCancellation(res.applycancellation);
    });
    setComponents({
      header: {
        cell: ResizeableTitle,
      },
    });
  }, []);

  const ResizeableTitle = (props: any) => {
    const { onResize, width = 100, ...restProps } = props;
    if (!width) {
      return <th {...restProps} />;
    }

    return (
      <Resizable width={width} height={38} onResize={onResize}>
        <th {...restProps} />
      </Resizable>
    );
  };
  const handleResize =
    (index: any) =>
    (e: any, { size }: any) => {
      const nextColumns = [...columns];
      nextColumns[index] = {
        ...nextColumns[index],
        width: size.width,
      };
      setAcolumns(nextColumns);
    };
  const columns = acolumns.map((col, index) => ({
    ...col,
    onHeaderCell: () => ({
      width: col.width || 100,
      onResize: handleResize(index),
    }),
  }));
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const onSelectChange = (newSelectedRowKeys: any) => {
    console.log(newSelectedRowKeys[0], 669999);
    request('/api/ljf/applyleaveget', {
      method: 'post',
      data: { _id: newSelectedRowKeys[0] },
    }).then((res: any) => {
      setAnumber(res.item[0].anumber);
      setStartTime(res.item[0].startTime);
      setEndtTime(res.item[0].endTime);
    });
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  return (
    <div className="applyLeave">
      <div className="applyleave">
        <button
          onClick={() => {
            applySubmit();
          }}
        >
          保存
        </button>
        <button>保存且新增</button>
        <button>草稿箱</button>
        <button>提交审批</button>
        <button>流程图</button>
        <button>导入</button>
      </div>
      <div className="applyLeaveContent applyLeaveContent0">
        <h1>销假申请单</h1>
        <table className="table">
          <tbody>
            <tr>
              <td>单据编号：</td>
              <td>
                <ProFormText
                  name="tnumber"
                  disabled
                  value={tnumber}
                  placeholder="保存后自动生成"
                />
              </td>
              <td>
                <span>*</span> 员工姓名：
              </td>
              <td>
                <ProFormText width="md" name="name" disabled value={aname} />
              </td>
              <td>
                <span>*</span> 员工部门：
              </td>
              <td>
                <ProFormText
                  width="md"
                  name="name"
                  disabled
                  value={department}
                />
              </td>
            </tr>
            <tr>
              <td>
                <span>*</span> 员工岗位：
              </td>
              <td>
                <ProFormText
                  width="md"
                  name="prodepartment"
                  disabled
                  value={prodepartment}
                />
              </td>
              <td>
                <span>*</span> 销假时间：
              </td>
              <td>
                <ProFormText
                  width="md"
                  name="name"
                  disabled
                  value={cancellationTime}
                />
              </td>
              <td>
                <span>*</span>原请假流程：
              </td>
              <td>
                <ProFormText name="anumber" value={anumber} placeholder={''} />
                <SearchOutline
                  className="searchoutline"
                  onClick={() => {
                    setIsApplyModalOpen(true);
                  }}
                />
              </td>
            </tr>
            <tr>
              <td>
                <span>*</span> 申请开始时间：
              </td>
              <td>
                <ProFormText
                  name="startTimeV"
                  disabled
                  value={startTime}
                  placeholder={''}
                  onChange={(e: any) => {
                    setStartTime(e._d);
                  }}
                />
              </td>
              <td>
                <span>*</span> 申请结束时间：
              </td>
              <td>
                <ProFormText
                  name="endTime"
                  disabled
                  value={endTime}
                  placeholder={''}
                  onChange={(e: any) => {
                    setEndtTime(e._d);
                  }}
                />
              </td>
              <td>是否已休假：</td>
              <td>
                <ProFormRadio.Group
                  name="radio"
                  value={Iscancellation}
                  onChange={(e: any) => {
                    setIscancellation(e.target.value);
                  }}
                  options={[
                    {
                      label: '是',
                      value: '是',
                    },
                    {
                      label: '否',
                      value: '否',
                    },
                  ]}
                />
              </td>
            </tr>
            <tr>
              <td>
                <span>*</span> 实际开始时间：
              </td>
              <td>
                <ProFormDateTimePicker
                  name="date"
                  placeholder={''}
                  initialValue={startTimeV}
                  onChange={(e: any) => {
                    setStartTimeV(e._d);
                  }}
                />
              </td>
              <td>
                <span>*</span> 实际结束时间：
              </td>
              <td>
                <ProFormDateTimePicker
                  name="date"
                  placeholder={''}
                  initialValue={endTimeV}
                  onChange={(e: any) => {
                    setEndtTimeV(e._d);
                  }}
                />
              </td>
              <td>
                <span>*</span> 已休天数：
              </td>
              <td>
                <ProFormText
                  width="md"
                  name="name"
                  disabled
                  value={oldDays}
                  placeholder=""
                />
              </td>
            </tr>
            <tr>
              <td>销假事由：</td>
              <td colspan={5}>
                <input
                  type="text"
                  value={technological}
                  onChange={(e) => {
                    setTechnological(e.target.value);
                  }}
                />
              </td>
            </tr>
          </tbody>
        </table>
        <table className="table0">
          <tbody>
            <tr>
              <td colspan={9}>
                附件上传<button>批量上传</button>
              </td>
            </tr>
            <tr>
              <td>文件名称</td>
              <td>文件大小</td>
              <td>上传人</td>
              <td>上传时间</td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td colspan={9}></td>
            </tr>
          </tbody>
        </table>
      </div>
      <Modal
        className="modalopen"
        title="提示对话框"
        open={isModalOpen}
        onCancel={ModalFalse}
        footer={null}
      >
        <div className="content">
          <span>i</span>
          <p>请输入{keyWord}</p>
          <button onClick={handleCancel}>确定</button>
        </div>
        
      </Modal>
      <Modal
        title="原请假流程"
        open={isApplyModalOpen}
        onCancel={handleCancel}
        footer={null}
        className="modalIsopen"
      >
        <div className="applyleave">
          <button
            onClick={() => {
              setIsApplyModalOpen(false);
            }}
          >
            确定
          </button>
          <button>取消</button>
        </div>
        <Table
          components={components}
          columns={columns}
          pagination={false}
          bordered
          rowKey="_id"
          scroll={{
            x: 1278,
            y: 400,
          }}
          rowSelection={{
            type: 'radio',
            ...rowSelection,
          }}
          onRow={(record, index) => {
            return {
              onClick: (e) => {
                let tr = e.target.parentNode;
                for (let i = 0; i < tr.parentNode.childNodes.length; i++) {
                  tr.parentNode.childNodes[i].style.color = 'black';
                }
                tr.style.color = '#e17009';
              },
            };
          }}
          dataSource={cancellation}
        />
        <div className="alpplybottom">
          <span className="iconfont icon-xiangzuoshuangjiantou"></span>
          <span className="iconfont icon-xiangzuojiantou"></span>
          <span className="iconfont icon-vertical_line"></span>
          第
          <Input value={1} />
          页，共1页
          <span className="iconfont icon-vertical_line"></span>
          <span className="iconfont icon-xiangyoujiantou"></span>
          <span className="iconfont icon-xiangyoushuangjiantou"></span>
          <span className="iconfont icon-vertical_line"></span>
          每页记录数：
          <Input value={50} />
          <Button>确定</Button>
        </div>
      </Modal>
    </div>
  );
}
